import { defineStore } from 'pinia'
import { sendMessage as apiSendMessage } from '../services/api.js'

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [],
    model: 'openai',
    sessionId: Date.now(),
    ws: null,
    streamMode: true, // 是否流式输出
  }),
  actions: {
    async sendMessage(message) {
      if (!message) return
      this.messages.push({ role: 'user', content: message })

      if (this.streamMode) {
        // 流式模式
        if (this.ws) {
          this.ws.close()
          this.ws = null
        }

        const ws = new WebSocket(`ws://127.0.0.1:8000/ws/chat?session_id=${this.sessionId}`)
        this.ws = ws

        // 新增 AI 消息占位
        this.messages.push({ role: 'ai', content: '', incomplete: true })

        ws.onopen = () => ws.send(JSON.stringify({ model: this.model, message }))
        ws.onmessage = ev => {
          const lastMsg = this.messages[this.messages.length - 1]
          if (lastMsg && lastMsg.role === 'ai' && lastMsg.incomplete) {
            if (ev.data === '__STREAM_END__') {
              lastMsg.incomplete = false
              ws.close()
              this.ws = null
            } else {
              lastMsg.content += ev.data
            }
          }
        }
        ws.onerror = () => {
          if (this.ws) this.ws.close()
          this.ws = null
        }
        ws.onclose = () => { this.ws = null }
      } else {
        // 普通模式
        const reply = await apiSendMessage(this.model, message, this.sessionId)
        this.messages.push({ role: 'ai', content: reply })
      }
    },

    setModel(model) { this.model = model },
    clearMessages() { this.messages = [] },
    toggleStreamMode() { this.streamMode = !this.streamMode },
  },
})
